package com.firefly.admin.config.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefly.admin.common.constant.Constants;
import com.firefly.admin.common.enums.ResultCodeEnum;
import com.firefly.admin.common.exception.BusinessException;
import com.firefly.admin.common.utils.RedisUtil;
import com.firefly.admin.common.vo.Result;
import com.firefly.admin.config.entity.FySystemDictionary;
import com.firefly.admin.config.entity.FySystemDictionaryItem;
import com.firefly.admin.config.mapper.FySystemDictionaryMapper;
import com.firefly.admin.config.service.FySystemDictionaryItemService;
import com.firefly.admin.config.service.FySystemDictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.firefly.admin.config.vo.SystemDictionaryQueryVo;
import com.firefly.admin.config.vo.SystemDictionaryStatusUpdateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Slf4j
public class FySystemDictionaryServiceImpl implements FySystemDictionaryService {
    @Autowired
    private FySystemDictionaryMapper fySystemDictionaryMapper;
    @Autowired
    private FySystemDictionaryItemService fySystemDictionaryItemService;

    @Override
    public List<FySystemDictionary> getAllDictionary() {
        LambdaQueryWrapper<FySystemDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemDictionary::getDictionaryStatus, Constants.Status.ENABLE);
        queryWrapper.orderByDesc(FySystemDictionary::getDictionaryId);
        return fySystemDictionaryMapper.selectList(queryWrapper);
    }

    /**
     * 分页查询系统字典接口
     *
     * @param systemDictionaryQueryVo 分页查询参数
     * @return 分页列表
     */
    @Override
    public Result<Page<FySystemDictionary>> getSystemDictionaryList(SystemDictionaryQueryVo systemDictionaryQueryVo) {
        log.info("###########FySystemDictionaryServiceImpl getSystemDictionaryList param = {}", JSONObject.toJSONString(systemDictionaryQueryVo));
        LambdaQueryWrapper<FySystemDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(systemDictionaryQueryVo.getDictionaryName()), FySystemDictionary::getDictionaryName, systemDictionaryQueryVo.getDictionaryName());
        queryWrapper.like(StringUtils.isNotBlank(systemDictionaryQueryVo.getDictionaryCode()), FySystemDictionary::getDictionaryCode, systemDictionaryQueryVo.getDictionaryCode());
        queryWrapper.eq(StringUtils.isNotBlank(systemDictionaryQueryVo.getDictionaryStatus()), FySystemDictionary::getDictionaryStatus, systemDictionaryQueryVo.getDictionaryStatus());
        queryWrapper.eq(FySystemDictionary::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        queryWrapper.orderByDesc(FySystemDictionary::getDictionaryId);
        Page<FySystemDictionary> page = new Page<>(systemDictionaryQueryVo.getPage(), systemDictionaryQueryVo.getLimit());
        Page<FySystemDictionary> systemDictionaryPage = fySystemDictionaryMapper.selectPage(page, queryWrapper);
        return Result.success(systemDictionaryPage);
    }

    /**
     * 获取系统字典信息接口
     *
     * @param dictionaryId 字典ID
     * @return 字典信息
     */
    @Override
    public Result<FySystemDictionary> getSystemDictionary(Long dictionaryId) {
        if (dictionaryId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemDictionary fySystemDictionary = fySystemDictionaryMapper.selectById(dictionaryId);
        if (fySystemDictionary == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DICTIONARY_NOT_FOUND);
        }
        List<FySystemDictionaryItem> dictionaryItemList = fySystemDictionaryItemService.findByDictionaryId(dictionaryId);
        fySystemDictionary.setItemList(dictionaryItemList);
        return Result.success(fySystemDictionary);
    }

    /**
     * 系统字典信息新增接口
     *
     * @param fySystemDictionary 字典信息
     * @return 操作结果
     */
    @Override
    public Result<FySystemDictionary> add(FySystemDictionary fySystemDictionary) {
        if (fySystemDictionary == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        ResultCodeEnum resultCodeEnum = checkParam(fySystemDictionary);
        if (resultCodeEnum != null) {
            return Result.getResult(resultCodeEnum);
        }
        int rows = fySystemDictionaryMapper.insert(fySystemDictionary);
        if (rows <= 0) {
            throw new BusinessException(ResultCodeEnum.ADD_EXCEPTION.name());
        }
        return Result.success(fySystemDictionary);
    }

    /**
     * 系统字典信息编辑接口
     *
     * @param fySystemDictionary 字典信息
     * @return 操作结果
     */
    @Override
    public Result<FySystemDictionary> update(FySystemDictionary fySystemDictionary) {
        if (fySystemDictionary == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long dictionaryId = fySystemDictionary.getDictionaryId();
        if (dictionaryId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemDictionary systemDictionary = fySystemDictionaryMapper.selectById(dictionaryId);
        if (systemDictionary == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DICTIONARY_NOT_FOUND);
        }
        ResultCodeEnum resultCodeEnum = checkParam(fySystemDictionary);
        if (resultCodeEnum != null) {
            return Result.getResult(resultCodeEnum);
        }
        int rows = fySystemDictionaryMapper.updateById(fySystemDictionary);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        List<FySystemDictionaryItem> itemList = fySystemDictionaryItemService.findByDictionaryId(dictionaryId);
        if (CollectionUtils.isEmpty(itemList) || Constants.Status.DISABLE.equals(fySystemDictionary.getDictionaryStatus())) {
            RedisUtil.hdel(Constants.Redis.DICTION_KEY, systemDictionary.getDictionaryCode());
        } else {
            RedisUtil.hset(Constants.Redis.DICTION_KEY, systemDictionary.getDictionaryCode(), itemList);
        }
        return Result.success(fySystemDictionary);
    }

    /**
     * 系统字典状态编辑接口
     *
     * @param systemDictionaryStatusUpdateVo 状态信息
     * @return 操作结果
     */
    @Override
    public Result<FySystemDictionary> updateStatus(SystemDictionaryStatusUpdateVo systemDictionaryStatusUpdateVo) {
        if (systemDictionaryStatusUpdateVo == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        Long dictionaryId = systemDictionaryStatusUpdateVo.getDictionaryId();
        if (dictionaryId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemDictionary systemDictionary = fySystemDictionaryMapper.selectById(dictionaryId);
        if (systemDictionary == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_MENU_NOT_FOUND);
        }
        String dictionaryStatus = systemDictionaryStatusUpdateVo.getDictionaryStatus();
        if (StringUtils.isBlank(dictionaryStatus)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DICTIONARY_STATUS_NOT_NULL);
        }
        systemDictionary.setDictionaryStatus(dictionaryStatus);
        int rows = fySystemDictionaryMapper.updateById(systemDictionary);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.UPDATE_EXCEPTION);
        }
        List<FySystemDictionaryItem> itemList = fySystemDictionaryItemService.findByDictionaryId(dictionaryId);
        if (CollectionUtils.isEmpty(itemList) || Constants.Status.DISABLE.equals(dictionaryStatus)) {
            RedisUtil.hdel(Constants.Redis.DICTION_KEY, systemDictionary.getDictionaryCode());
        } else {
            RedisUtil.hset(Constants.Redis.DICTION_KEY, systemDictionary.getDictionaryCode(), itemList);
        }
        return Result.success(systemDictionary);
    }

    /**
     * 系统字典信息删除接口
     *
     * @param dictionaryId 字典ID
     * @return 操作结果
     */
    @Override
    public Result<String> delete(Long dictionaryId) {
        if (dictionaryId == null) {
            return Result.getResult(ResultCodeEnum.REQUEST_PARAM_EXCEPTION);
        }
        FySystemDictionary fySystemDictionary = fySystemDictionaryMapper.selectById(dictionaryId);
        if (fySystemDictionary == null) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DICTIONARY_NOT_FOUND);
        }
        String dictionaryCode = fySystemDictionary.getDictionaryCode();
        fySystemDictionaryItemService.deleteByDictionaryId(dictionaryId);
        fySystemDictionary.setDeleteFlag(Constants.DeleteFlag.DELETE);
        int rows = fySystemDictionaryMapper.updateById(fySystemDictionary);
        if (rows <= 0) {
            return Result.getResult(ResultCodeEnum.DELETE_EXCEPTION);
        }
        RedisUtil.hdel(Constants.Redis.DICTION_KEY, dictionaryCode);
        return Result.success();
    }

    /**
     * 系统字典编码校验接口
     *
     * @param dictionaryCode 字典编码
     * @param dictionaryId   字典ID
     * @return 校验结果
     */
    @Override
    public Result<String> dictionaryCodeCheck(String dictionaryCode, Long dictionaryId) {
        if (StringUtils.isBlank(dictionaryCode)) {
            return Result.getResult(ResultCodeEnum.SYSTEM_DICTIONARY_CODE_NOT_NULL);
        }
        LambdaQueryWrapper<FySystemDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemDictionary::getDictionaryCode, dictionaryCode);
        queryWrapper.eq(FySystemDictionary::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        List<FySystemDictionary> systemDictionaryList = fySystemDictionaryMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemDictionaryList)) {
            if (dictionaryId == null) {
                //新增
                return Result.success(ResultCodeEnum.SYSTEM_DICTIONARY_CODE_EXIST.getMsg());
            } else {
                //编辑
                for (FySystemDictionary systemDictionary : systemDictionaryList) {
                    if (dictionaryId.longValue() != systemDictionary.getDictionaryId().longValue()) {
                        return Result.success(ResultCodeEnum.SYSTEM_DICTIONARY_CODE_EXIST.getMsg());
                    }
                }
            }
        }
        return Result.success();
    }

    private ResultCodeEnum checkParam(FySystemDictionary fySystemDictionary) {
        String dictionaryName = fySystemDictionary.getDictionaryName();
        if (StringUtils.isBlank(dictionaryName)) {
            return ResultCodeEnum.SYSTEM_DICTIONARY_NAME_NOT_NULL;
        }
        Long dictionaryId = fySystemDictionary.getDictionaryId();
        String dictionaryCode = fySystemDictionary.getDictionaryCode();
        if (StringUtils.isBlank(dictionaryCode)) {
            return ResultCodeEnum.SYSTEM_DICTIONARY_CODE_NOT_NULL;
        }
        LambdaQueryWrapper<FySystemDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemDictionary::getDictionaryCode, dictionaryCode);
        queryWrapper.eq(FySystemDictionary::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        List<FySystemDictionary> systemDictionaries = fySystemDictionaryMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(systemDictionaries)) {
            if (dictionaryId == null) {
                //新增
                return ResultCodeEnum.SYSTEM_DICTIONARY_CODE_EXIST;
            } else {
                //编辑
                for (FySystemDictionary systemDictionary : systemDictionaries) {
                    if (systemDictionary.getDictionaryId().longValue() != dictionaryId.longValue()) {
                        return ResultCodeEnum.SYSTEM_DICTIONARY_CODE_EXIST;
                    }
                }
            }
        }
        String dictionaryStatus = fySystemDictionary.getDictionaryStatus();
        if (dictionaryId == null && StringUtils.isBlank(dictionaryStatus)) {
            fySystemDictionary.setDictionaryStatus(Constants.Status.ENABLE);
        }
        return null;
    }

    /**
     * 查询所有正常状态的字典
     *
     * @return 正常状态字典列表
     */
    @Override
    public List<FySystemDictionary> findAllNormal() {
        LambdaQueryWrapper<FySystemDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FySystemDictionary::getDictionaryStatus, Constants.Status.ENABLE);
        queryWrapper.orderByDesc(FySystemDictionary::getDictionaryId);
        queryWrapper.eq(FySystemDictionary::getDeleteFlag, Constants.DeleteFlag.NORMAL);
        return fySystemDictionaryMapper.selectList(queryWrapper);
    }
}
